<?php

namespace Qdr\Jwt;

class Jwt extends Rsa2
{
    /**
     * @param $params
     * @param $publicKey
     * @return string|null
     */
    public static function createToken($params = []) {
        $model = new self();
        $token = $model->setPublicKey(config("jwt.public_key"))->setParams($params)->setAuthorization();
        cache(md5($token), $params); // 缓存token和数据
        return $token;
    }
    
    /**
     * @param $token
     * @return array
     * @throws \Exception
     */
    public static function verifyToken($token) {
        $model = new self();
        [$time, $md5] = $model->setPrivateKey(config("jwt.private_key"))->getAuthorizationData($token);
        $return['params'] = cache(md5($token));
        if (!$time || !$md5 || !$return['params']) {
            throw new \Exception("token解密失败!" . $time . '-' . $md5. '-' . json_encode($return['params']));
        }
        $return['time'] = $time;
        $return['now_time'] = time();
        if ($md5 !== md5(json_encode($return['params'])) || $return['now_time'] - $time > config("jwt.refresh_ttl")) {
            cache(md5($token), null); // 清除旧数据
            throw new \Exception("登录缓存已过期!");
        }
        if ($return['now_time'] - $time > config("jwt.ttl")) {
            $return['token'] = self::createToken($return['params']); // 刷新新的token
            cache(md5($token), null); // 清除旧数据
        }
        return $return;
    }
    
    /**
     * @param $token
     * @return void
     * desc: 清除登陆
     */
    public static function clearToken(string $token):void {
        cache(md5($token), null); // 清除旧数据
        return;
    }
}